package com.ldu.exam.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ldu.exam.assistant.BeanAssistant;
import com.ldu.exam.dao.NoticeRepository;
import com.ldu.exam.model.NoticeModel;

@Service
public class NoticeService 
{
	@Autowired NoticeRepository repository;
	
	public Page<NoticeModel> findAll(String isRead,String accountId,Pageable page)
	{

		return this.findByCondition(isRead,accountId,page);
	}
	
	private Page<NoticeModel> findByCondition(String isRead,String accountId,Pageable page)
	{
		return this.repository.findAll( new Specification<NoticeModel>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<NoticeModel> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				List<Predicate> list = new ArrayList<Predicate>();
				if(!StringUtils.isEmpty(isRead))
				list.add(builder.equal( root.<String>get("isRead"), isRead));
				if(!StringUtils.isEmpty(accountId))
				list.add(builder.equal( root.<String>get("accountId"), accountId));
				Predicate[] pd=list.toArray( new Predicate[list.size()]);
				return builder.and(pd);
			}
		},page);
	}
	
	public Object add(NoticeModel model)
	{
		return null;
	}
	
	public Object update(String id , NoticeModel model)
	{
		model.setId( null);
		NoticeModel nm = this.repository.findById(id).orElse(null);
		String [] nullPropertyNames = BeanAssistant.getNullPropertyNames( model) ;
		BeanUtils.copyProperties( model, nm, nullPropertyNames);
		return this.repository.save( nm);
	}
	
	public Object onRead(String id , String isRead)
	{
		NoticeModel model = new NoticeModel();
		model.setIsRead(isRead);
		return this.update(id, model);
	}
	
}
